<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { ID } from '#/api/common';

import { computed, onMounted, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Anchor, message, Space, Spin } from 'ant-design-vue';

import { useVbenVxeGrid, vxeCheckboxCheckedCount } from '#/adapter/vxe-table';
import { employeeQueryByCompanyIdGroupPosition } from '#/api/company/audience';
import addEmployeeToFavoriteModal from '#/components/favorite/src/add-employee-modal.vue';

const props = defineProps<{ companyId: ID }>();

const loading = ref(false);
const tableRefList = ref<any>([]);

const columns: VxeGridProps['columns'] = [
  { type: 'checkbox', width: 60 },
  {
    title: '姓名',
    field: 'name',
    width: 100,
  },
  {
    title: '部门',
    field: 'department',
  },
  {
    title: '职位',
    field: 'position',
  },
  {
    title: '数据来源',
    field: 'sourceName',
  },
  {
    title: '到场明细',
    field: 'regCapitalStr',
  },
  {
    title: '创建时间',
    field: 'createTime',
  },
  {
    field: 'action',
    fixed: 'right',
    slots: { default: 'action' },
    title: '操作',
    width: 130,
  },
];

async function loadList() {
  try {
    loading.value = true;
    const data = await employeeQueryByCompanyIdGroupPosition(props.companyId);
    tableRefList.value = Object.entries(data).map(([key, value], index) => {
      const gridOptions: VxeGridProps = {
        columns,
        // height: 'auto',
        keepSource: true,
        pagerConfig: {
          enabled: false,
        },
        proxyConfig: {
          ajax: {
            query: async () => {
              return { rows: value };
            },
          },
        },
        toolbarConfig: {
          refresh: false,
        },
        scrollY: {
          enabled: true,
          gt: 0,
        },
        rowConfig: {
          keyField: 'id',
        },
        id: `employee-network-table-${index}`,
        showOverflow: true,
      };
      const [GroupTable, tableApi] = useVbenVxeGrid({
        gridOptions,
        gridEvents: {
          checkboxChange: checkBoxEvent,
          checkboxAll: checkBoxEvent,
        },
      });
      return {
        id: index,
        key,
        table: [GroupTable, tableApi],
        total: value.length,
      };
    });
    loading.value = false;
  } catch (error) {
    console.log(error);
    loading.value = false;
  }
}

// 批量加入收藏夹
const [AddEmployeeToFavoriteModal, addEmployeeToFavoriteModalApi] =
  useVbenModal({
    connectedComponent: addEmployeeToFavoriteModal,
    destroyOnClose: true,
  });

const checkedTotal = ref(0);

function checkBoxEvent() {
  const sums = tableRefList.value.map((item: any) => {
    return vxeCheckboxCheckedCount(item.table?.[1]);
  });
  checkedTotal.value = sums.reduce(
    (total: number, num: number) => total + num,
    0,
  );
}

function handleFavorite() {
  // 勾选加入
  const recordAll: any = [];
  tableRefList.value.forEach((item: any) => {
    const tableApi = item.table?.[1];
    const records = tableApi.grid.getCheckboxRecords();
    recordAll.push(...records);
  });
  addEmployeeToFavoriteModalApi.setData({
    type: 'check',
    records: recordAll,
    total: recordAll.length,
  });
  addEmployeeToFavoriteModalApi.open();
}

function handleContactLog(row: any) {
  console.log(row);
  message.warning('待开发...');
}

// 锚点事件
const anchors = computed(() => {
  return tableRefList.value.map((item: any) => {
    return {
      key: `position${item.id}`,
      href: `#position${item.id}`,
      title: item.key,
    };
  });
});

function handleAnchorClick(e: any, link: any) {
  e.preventDefault();
  if (link?.href) {
    const el = document.querySelector(link.href);
    el?.scrollIntoView({ block: 'end', behavior: 'smooth' });
  }
}

onMounted(() => {
  loadList();
});
</script>

<template>
  <Spin v-if="loading" spinning class="w-full" />
  <div v-else>
    <div class="flex items-start justify-center gap-2">
      <div class="flex flex-1 flex-col">
        <Space size="large" class="mb-[10px] flex justify-end">
          <a-button :disabled="checkedTotal === 0" @click="handleFavorite">
            添加到收藏夹({{ checkedTotal }})
          </a-button>
        </Space>

        <div
          v-for="(item, index) in tableRefList"
          :key="index"
          class="mb-[20px]"
          :id="`position${item.id}`"
        >
          <component :is="item.table[0]">
            <template #table-title>
              <main-title :text="`${item.key} (${item.total})`" />
            </template>
            <template #action="{ row }">
              <Space>
                <ghost-button @click.stop="handleContactLog(row)">
                  联络记录
                </ghost-button>
              </Space>
            </template>
          </component>
        </div>
      </div>
      <div class="mt-[80px]">
        <Anchor
          affix
          :offset-top="200"
          :items="anchors"
          @click="handleAnchorClick"
        />
      </div>
    </div>
    <AddEmployeeToFavoriteModal @reload="loadList" />
  </div>
</template>
